<template>
    <div>
        <template v-if='formData.strategy.length > 0'>
            <a-form ref='formRef' autocomplete='off' :model='formData' :label-col='{ span: 4 }' :wrapper-col="{ span: 18 }" @finish='submit'>
                <a-card :class='$style.nameCard' :bordered='false'>
                    <a-form-item label='标题' name='name' :rules='[{required : true, message : "请填写标题"}]'>
                        <a-input v-model:value='formData.name' />
                    </a-form-item>
                </a-card>
                <template v-for='(strategy, index) in formData.strategy' :key='index'>
                    <a-card :class='$style.formData'>
                        <a-form-item label='股票名称'>
                            <a-input :value='shares[index].codeName' :bordered='false' readonly type='text' />
                        </a-form-item>
                        <a-form-item label='策略名称'>
                            <a-input :value='shares[index].name' :bordered='false' readonly type='text' />
                        </a-form-item>

                        <a-form-item style="display:none" label='code' :name='["strategy", index, "code"]'>
                            <a-input type='hidden' :value='strategy.code' :bordered='false' readonly />
                        </a-form-item>
                        <a-form-item style="display:none" label='策略Id' :name='["strategy", index, "strategy_id"]'>
                            <a-input type='hidden' :value='strategy.strategy_id' :bordered='false' readonly />
                        </a-form-item>
                        
                        <a-form-item label='回测金额' :rules='[{required : true, message : "请填写回测金额"}]' :name='["strategy", index, "cash"]'>
                            <a-input v-model:value.number='strategy.cash' type='number' />
                        </a-form-item>
                        <template v-for='(field, i) in strategy.fields' :key='i'>
                            <a-form-item :label='field.name' :rules='field.rules' :name='["strategy", index, field.code]'>
                                <template v-if='field.type == 1'>
                                    <a-input v-model:value='strategy[field.code]' />
                                </template>
                                <template v-else-if='field.type == 6'>
                                    <XStockSelect :type='field.code_list' v-model:value='strategy[field.code]' />
                                </template>
                                <template v-else>
                                    <a-select v-model:value='strategy[field.code]' :options='field.options'></a-select>
                                </template>
                            </a-form-item>
                        </template>
                    </a-card>
                </template>
                <a-card :bordered='false' :class='$style.formData'>
                    <a-form-item label='基准' :rules='[{required : true, message : "请选择基准"}]' name='benchmark'>
                        <a-select v-model:value='formData.benchmark' :options='BENCHMARK'></a-select>
                    </a-form-item>

                    <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
                        <a-button type='primary' html-type='submit' :loading='loading'>开始跟踪</a-button>
                    </a-form-item>
                </a-card>
            </a-form>
        </template>
        <template v-else>
            <a-skeleton active />
        </template>

        
    </div>
</template>

<script lang='ts' setup>
    import { strategyTradeStartApi, strategyTradeRunApi } from '@/api/strategy'
    import { reactive, ref } from '@vue/reactivity'
    import { useRoute, useRouter } from 'vue-router'
    import { BENCHMARK } from '@/constant'
import { message } from 'ant-design-vue'


    const $route = useRoute()
    const $router = useRouter()

    const loading = ref(false)
    const packageId = Number($route.params.id)

    const shares = reactive<any[]>([])

    const formData = reactive<any>({
        name : '新建组合回测',
        benchmark : '',
        strategy : []
    })


    strategyTradeStartApi({package_id: packageId, is_batch: 1}).then(data => {
        data.forEach(item => {
            shares.push({
                codeName : item.code_name,
                name : item.name,
            })


            let strategy:any = {
                code : item.code,
                strategy_id : item.id,
                cash : '',
                fields : []
            }

            if(item.attr && item.attr.length > 0) {
                item.attr.forEach(attr => {
                    strategy[attr.code] = ''
                    let field:any = {
                        name : attr.name,
                        type : attr.type,
                        code : attr.code,
                    }

                    if(attr.type == 2) {
                        const options = JSON.parse(attr.value)
                        field.options = Object.keys(options.list).map(key => ({value : key, label : options.list[key]}))
                        field.rules = [{required : options.required === 'ture', message : '请选择' + attr.name}] 
                    }else if(attr.type == 6) {
                        const option = JSON.parse(attr.value)
                        field.code_list = option.code_list
                        field[item.code] = [{required : option.required === 'ture', message : '请选择' + attr.name}] 
                    }else {
                        if(attr.value) {
                            try {
                                const option = JSON.parse(attr.value)
                                if(option) {
                                    let rule:any = {
                                        required : option.required === 'ture',
                                        validator : (_rule, value) => {
                                            if(value === '') {
                                                if(option.required) {
                                                    
                                                    return Promise.reject('请填写' + attr.name);
                                                }else {
                                                    return Promise.resolve()
                                                }
                                                
                                            }

                                            if(option.number) {
                                                value = Number(value)
                                                if(isNaN(value)) {
                                                    return Promise.reject('请输入数字');
                                                }
                                                if('min' in option.number && value < option.number.min) {
                                                    return Promise.reject(attr.name + `不能小于${option.number.min}`);
                                                }

                                                if('max' in option.number && value > option.number.max) {
                                                    return Promise.reject(attr.name + `不能大于${option.number.max}`);
                                                }
                                            }

                                            return Promise.resolve()
                                        }
                                        
                                    }
                                    

                                    field.rules = [rule]

                                }

                            } catch (error) {
                                console.log('-----------------')
                                console.log(error)
                            }
                        }
                    }

                    
                    strategy.fields.push(field)

                })
            }

            formData.strategy.push(strategy)
        })
    })

    async function submit(values) {
        let params:any = JSON.parse(JSON.stringify(values))
        loading.value = true
        const res = await strategyTradeRunApi(params)
        loading.value = false
        if(res.success) {
            $router.replace('/strategy/follow/' + res.data.package_id)
        }else {
            message.error(res.message)
        }
    }

</script>


<style lang='scss' module>
.nameCard {
        :global(.ant-card-body){
            padding-bottom: 0;
            padding-top: 0;
        }

        :global(.ant-form-item){
             margin-bottom: 0 !important;
        }
    }
    .form{
        width: 600px;
        margin: auto;
    }

    .formData{
        margin-top: 20px;
        &:first-child{
            margin-top: 0;
        }

        :global(.ant-form-item){
            &:last-child{
                margin-bottom: 0 !important;
            }
        }
    }

</style>